//
//  RootViewController.m
//  NewsReader
//
//  Created by blacksun on 10-10-17.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "RootViewController.h"
#import "SettingViewController.h"

@implementation RootViewController
@synthesize sections,scrollView,sectionViewControllers,needDeleteSections,needDeleteControllers,pagecontrol,needAddSections,settingImageView;
@synthesize activityView;
@synthesize theHttpUtils;

#pragma mark -
#pragma mark View lifecycle

-(IBAction)didClickSetting:(id)sender{
	SettingViewController *controller = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	controller.user = delegate.user;
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}

- (void)longPress:(id)sender{
	if (![HttpUtil isNetworkUseable]) {
		[HttpUtil showUsageAlertDialog];
		return;
	}
	for (int i=0; i<[self.sectionViewControllers count]; i++) {
		id sectionController = [self.sectionViewControllers objectAtIndex:i];
		if ([sectionController respondsToSelector:@selector(needToDeleteMySelf)]) {
			[sectionController performSelector:@selector(needToDeleteMySelf)];
		}
	}
	[self.needDeleteSections removeAllObjects];
	[self.needDeleteControllers removeAllObjects];
	
	UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(finishEdit:)];
	self.navigationItem.rightBarButtonItem = rightButton;
	[rightButton release];
	[self.navigationController setNavigationBarHidden:NO animated:YES];
	

}
-(void)finishEdit:(id)sender{
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	self.navigationItem.rightBarButtonItem = nil;
	[self.navigationController setNavigationBarHidden:YES animated:YES];
	for (int i=0; i<[self.sectionViewControllers count]; i++) {
		id sectionController = [self.sectionViewControllers objectAtIndex:i];
		if ([sectionController respondsToSelector:@selector(resumeNormal)]) {
			[sectionController performSelector:@selector(resumeNormal)];
		}
	}
	if ([self.needDeleteSections count]==0) {
		return;
	}
	
	[self.sections removeObjectsInArray:self.needDeleteSections];
	[self.sectionViewControllers removeObjectsInArray:self.needDeleteControllers];
	//NSLog(@"deleted,size=%d",[delegate.user.mySections count]);
	[delegate archiverUser:delegate.user];
	
	NSMutableArray *needDeleteSectionsId = [[NSMutableArray alloc] init];
	for (Section *needDeleteSection in self.needDeleteSections) {
		[needDeleteSectionsId addObject: [NSString stringWithFormat:@"%@",needDeleteSection.sectionId]];
	}
	NSString *ids = [needDeleteSectionsId componentsJoinedByString:@","];
	
	NSString *urlStr = [URLAddress deleteMySections:ids forMe:delegate.user.userId];
	//NSLog(@"%@",urlStr);
	NSURL *url = [[NSURL alloc] initWithString:urlStr];
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
	HttpUtil *httpUtil = [[HttpUtil alloc] init];
	[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(finishHttpRequest:) isBackGround:NO];
	
	[httpUtil release];
	[request release];
	[url release];
	[needDeleteSectionsId release];
	[self.needDeleteSections removeAllObjects];
}

-(void)finishHttpRequest:(NSData *)response{
	[response release];
}
  

- (void)viewDidLoad {
    [super viewDidLoad];
	[self.activityView stopAnimating];
	self.scrollView.delegate = self;
	self.needAddSections = [NSMutableArray array];
	self.theHttpUtils = [NSMutableArray array];
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	self.sections =  delegate.user.mySections;
	self.sectionViewControllers = [NSMutableArray array];
	self.needDeleteSections = [NSMutableArray array];
	self.needDeleteControllers = [NSMutableArray array];
	UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
	longPress.minimumPressDuration = 1;
	[self.scrollView addGestureRecognizer:longPress];
	[longPress release];
	
	[self setUpSectionView:self.sections];
	
	
}
/**
 * 构建首页的section视图
 */
- (void)setUpSectionView:(NSArray*)theSections{
	for (int i=0; i<[self.sectionViewControllers count]; i++) {
		UIViewController *controller = [self.sectionViewControllers objectAtIndex:i];
		[controller.view removeFromSuperview];
	}
	[self.sectionViewControllers removeAllObjects];
	
	for (int i=0; i<[theSections count]; i++) {
		SectionViewController *sectionController = [[SectionViewController alloc] initWithNibName:@"SectionViewController" bundle:nil];
		sectionController.section = [theSections objectAtIndex:i];
		sectionController.view.alpha = 0.1;
		[self.sectionViewControllers addObject:sectionController];
		[sectionController release];
	}
	AddSectionController *addSectionController = [[AddSectionController alloc] initWithNibName:@"AddSectionController" bundle:nil];
	[self.sectionViewControllers addObject:addSectionController];
	[addSectionController release];
	
	self.pagecontrol.numberOfPages = [ModelParseUtil reloadScrollView:self.scrollView withControllers:self.sectionViewControllers needAnimation:NO startIndex:0];
	[ModelParseUtil addAnimationForSections:self.sectionViewControllers];
}

- (void)viewWillAppear:(BOOL)animated {
	
    [super viewWillAppear:animated];
	
	/**
	 当程序重新激活后，delegate.user.mysections是从文件中获取的对象，如果不从新设置section，在订阅时候会引发问题。
	 */
		for (int j=0; j<[self.sections count]; j++) {
			Section *mySection = [self.sections objectAtIndex:j];
			for (int i=0; i<[self.sectionViewControllers count]-1; i++) {
				SectionViewController *controller = (SectionViewController *)[self.sectionViewControllers objectAtIndex:i];
				Section *temp = controller.section;
				
				if ([temp.sectionId isEqualToString:mySection.sectionId]) {
					controller.section = mySection;
					[controller updateImage];
				}
				
			}
		}
	
	
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	
	//NSLog(@"root view will appera");
	self.navigationController.navigationBar.translucent = YES;
	self.navigationController.navigationBarHidden = YES;
	//如果有需要订阅的section，则发出订阅请求
	if ([self.needAddSections count]==0) 
		return;
	if (!delegate.networkState) {
		return;
	}
	
	//首先保存在主页中创建section并保存
	[self.sections addObjectsFromArray:self.needAddSections];
	for (Section *selected in self.needAddSections) {
		SectionViewController *sectionViewController = [[SectionViewController alloc] initWithNibName:@"SectionViewController" bundle:nil];
		sectionViewController.section = selected;
		[self.sectionViewControllers insertObject:sectionViewController atIndex:[self.sectionViewControllers count]-1];
		[sectionViewController release];
	}
	self.pagecontrol.numberOfPages = [ModelParseUtil reloadScrollView:self.scrollView withControllers:self.sectionViewControllers
														needAnimation:NO startIndex:0];
	//当添加订阅后，立即保存user对象。
	[delegate archiverUser:delegate.user];
	
	//发出添加订阅的请求
	NSMutableArray *ids = [[NSMutableArray alloc] init];
	for (Section *selected in self.needAddSections) {
		[ids addObject:[NSString stringWithFormat:@"%@", selected.sectionId]];
	}
	NSString *idStrs = [[NSString alloc] initWithFormat:@"%@",[ids componentsJoinedByString:@","]];
	NSString *urlStr = [URLAddress addSections:idStrs forMe:delegate.user.userId];
	NSURL *url = [[NSURL alloc] initWithString:urlStr];
	//NSLog(@"%@",[URLAddress addSections:idStrs forMe:delegate.user.userId]);
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
	HttpUtil *httpUtil = [[HttpUtil alloc] init];
	[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(subcribeSectionsSuccess:) isBackGround:NO];
	
	[httpUtil release];
	[request release];
	[url release];
	[idStrs release];
	[ids release];
	
	[self.needAddSections removeAllObjects];	
	
}

-(void)subcribeSectionsSuccess:(NSData *)response{
	[response release];
		
}



- (void)viewDidAppear:(BOOL)animated {
	//NSLog(@"root view did appera");
    [super viewDidAppear:animated];
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	if (!delegate.networkState) {//网络不可用
		self.settingImageView.image = [UIImage imageNamed:@"setting_un.png"];
		[HttpUtil showUsageAlertDialog];
		return;
	}else {//网络可用
		self.settingImageView.image = [UIImage imageNamed:@"setting_new.png"];
	}

	if (!delegate.user.needUpdateSections) {
		return;
	}
	
	if(!delegate.user.userId ||[delegate.user.userId isEqualToString:kUser_defaultUserId]){//如果用户id为空，则重新进行匿名注册
		[self.activityView startAnimating];
		for (int i=0; i<[self.sectionViewControllers count]; i++) {
			id sectionController = [self.sectionViewControllers objectAtIndex:i];
			if ([sectionController respondsToSelector:@selector(needToDeleteMySelf)]) {
				[sectionController performSelector:@selector(needToDeleteMySelf)];
			}
		}
		NSURL *url = [[NSURL alloc] initWithString:[URLAddress anonymousRegister:delegate.user.deviceId]];
		NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
		HttpUtil *httpUtil = [[HttpUtil alloc] init];
		[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(finishGetUserIdRequest:) isBackGround:YES];
		[self.theHttpUtils addObject:httpUtil];
		[httpUtil release];
		[url release];
		[request release];
		
		
	}
		
}

- (void)gaeIsGFW{//设置GAE被墙，发起更新section的请求
	[self.activityView stopAnimating];
	if ([self.theHttpUtils count] == 0) return;
	[self.theHttpUtils makeObjectsPerformSelector:@selector(stopHttpConnection)];
	[self.theHttpUtils removeAllObjects];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	delegate.isGFW = YES;
	NSLog(@"isGFW");
	[self viewDidAppear:YES];
}

- (void)finishGetUserIdRequest:(NSData *)theResponse{
	[self.theHttpUtils removeAllObjects];
	[self.activityView stopAnimating];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	NSString *responseStr = [[NSString alloc] initWithData:theResponse encoding:NSUTF8StringEncoding];
	NSDictionary * responseDict = [responseStr JSONValue];
	delegate.user.userId = [NSString  stringWithFormat:@"%@",[responseDict objectForKey:kUserId]];
	NSArray *sectionsArray = [responseDict objectForKey:kDefaultSections];
	delegate.user.mySections = [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
	self.sections = delegate.user.mySections;
	[delegate archiverUser:delegate.user];
	[self setUpSectionView:self.sections];
	[responseStr release];
	[theResponse release];
}


-(void)updateSections:(NSData *)response{
	[self.theHttpUtils removeAllObjects];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	delegate.user.needUpdateSections = NO;
	NSMutableArray *newSections = nil;
	NSString *responseStr = nil;
	if (response) {
		responseStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
		NSDictionary * responseDict = [responseStr JSONValue];
		NSArray *sectionsArray = [responseDict objectForKey:@"sections"];
		newSections = [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
		
	}else {
		newSections = [NSMutableArray array];
	}

	for (int i=0; i<[self.sections count]; i++) {
		Section *old = [self.sections objectAtIndex:i];
		for (int j=0; j<[newSections count]; j++) {
			Section *temp = [newSections objectAtIndex:j];
			if ([temp.sectionId isEqualToString:old.sectionId]) {
				old.oldFeedTitle = old.lastFeedTitle;
				//NSLog(@"old title=%@",old.lastFeedTitle);
				old.oldImageUrl = old.lastFeedImageUrl;
				old.lastFeedTitle = temp.lastFeedTitle;
				old.lastFeedImageUrl = temp.lastFeedImageUrl;
				old.currentMaxId = temp.currentMaxId;
				break;
			}
		}
		[(SectionViewController *)[self.sectionViewControllers objectAtIndex:i] updateImage];
	}
	[responseStr release];
	[response release];
	
}


- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	[self finishEdit:nil];
}

/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pagecontrol.currentPage = page;
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[self.activityView release];
	[self.settingImageView release];
	[self.needDeleteSections release];
	[self.needDeleteControllers release];
	[self.sectionViewControllers release];
	[self.pagecontrol release];
	[self.scrollView release];
	[self.sections release];
	[self.needAddSections release];
	[self.theHttpUtils release];
    [super dealloc];
}


@end

